package com.cx.mall.pay.controller;

import com.cx.mall.common.entity.order.entity.OrderInfo;
import com.cx.mall.common.util.ResponseVo;
import com.cx.mall.pay.config.AlipayConfiguration;
import com.cx.mall.pay.service.IAliPayService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/alipay")
public class ALiPayController {

    @Autowired
    private IAliPayService aliPayService;
    @Autowired
    private AlipayConfiguration alipayConfiguration;


    @GetMapping("/pay")
    public ResponseVo pay(OrderInfo orderInfo, HttpServletResponse response) {
        if (orderInfo == null) {
            throw new RuntimeException("订单信息不存在");
        }
      String result =  aliPayService.pay(orderInfo);
        response.setContentType("text/html;charset=utf-8");
        try {
            response.getWriter().write(result);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            throw new RuntimeException(e+"支付失败");
        }

        return ResponseVo.success();
    }
    //支付成功回调
    @GetMapping("/return")
    public ResponseVo payReturn(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            response.sendRedirect(alipayConfiguration.getSuccessUrl());
        } catch (IOException e) {
            throw new RuntimeException(e+"支付成功，跳转失败");
        }
        return ResponseVo.success();
    }

    // 支付成功落地页（供网关 /api/alipay/success 转发）
    @GetMapping("/success")
    public void success(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String qs = request.getQueryString();
        String target = "/alipay/success.html" + (qs != null ? ("?" + qs) : "");
        try {
            response.sendRedirect(target);
        } catch (IOException e) {
            throw new RuntimeException("跳转支付成功页失败", e);
        }
    }
    //异步支付通知，订单支付成功后，支付宝会向该地址发送支付结果通知，订单支付成功后，需要修改订单状态，待付款->代发货
    @PostMapping("/notify")
    public ResponseVo notify(HttpServletRequest request) {

       //获取支付宝返回的各个参数;
        Map<String, String[]> parameterMap = request.getParameterMap();
        log.info("支付宝异步通知状态:{}",parameterMap.get("trade_status")[0]);


        if("TRADE_SUCCESS".equals(parameterMap.get("trade_status")[0])){
            //异步通知
            aliPayService.payNotify(parameterMap);
            return ResponseVo.success();
        }else {
            //支付失败
            throw new RuntimeException("异步通知失败");
        }


    }



}
